package com.instalinks.android.apps.smspostservice;

import java.util.List;

import android.app.Activity;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.instalinks.android.apps.smspostservice.helper.AppConfig;
import com.instalinks.android.lib.AppHelper;
import com.instalinks.android.lib.ApplicationNotifications;
import com.instalinks.android.lib.LibConstants;

public class ErrorActivity extends Activity {

	// private final String ERR_NOEMAIL =
	// "To start <b><font color='#ff0000'>Thin Server</font></b>, you need to have atleast one <u>Google based email address</u> registered in your device";
	// private final String ERR_CONFIG =
	// "Unable to update configuration file. Please restart the application.";

	private String mError = "";
	private AppConfig mAppCfg;
	private TextView txtErrorText;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.error);

		try {
			Bundle bundle = this.getIntent().getExtras();
			mError = bundle.getString("error");
		} catch (Exception e) {
		}

		if (mError == null)
			mError = "Unknown Error. Restart the application. ";

		initialize();
	}

	private void initialize() {
		
		mAppCfg = new AppConfig(getApplicationContext());

		ApplicationNotifications appNotifications = mAppCfg.getExternalNotificationInstance();
		
		
		appNotifications.notifyClearAll();

		Button btnErrorClose = (Button) findViewById(R.id.btnErrorClose);

		txtErrorText = (TextView) findViewById(R.id.txtErrorText);

		if(mError.equals(LibConstants.Error.BASE_APP_ERR)){
			notifyBaseAppError();
		}else{
			txtErrorText.setText(Html.fromHtml(mError));
		}

		btnErrorClose.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				System.exit(0);
			}
		});
	}

	public final void notifyBaseAppError(){
		
		List<ResolveInfo> apps = AppHelper.lookForInstalledApp(getApplicationContext(), LibConstants.Packages.BASE_APP);
		
		if(apps.size() == 0){
			txtErrorText.setText("Base Application not installed. Check for 'Instalinks Apps' in Android Market");
		}else if(apps.size() == 1){
			txtErrorText.setText("Start the 'Instalinks Apps' service before using this app.");
		}else{
			txtErrorText.setText("Rare Case : More than 1 application with same package is installed");
		}
	}

}
